<template>
  <div>
    <div class="top-panel">
      <el-form :model="searchFormData" label-width="80px">
        <el-row>
          <el-col :span="5">
            <el-form-item prop="nickNameFuzzy" label="昵称 ">
              <el-input
                placeholder="请输入昵称"
                v-model.trim="searchFormData.nickNameFuzzy"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item prop="phoneFuzzy" label="手机号 ">
              <el-input
                placeholder="请输入手机号"
                v-model.trim="searchFormData.phoneFuzzy"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5" :style="{ 'padding-left': '10px' }">
            <el-button type="danger" @click="loadDataList">搜索</el-button>
            <el-button
              type="primary"
              @click="showEditUser('add')"
              v-if="userInfo.roleType === 1"
              >新增账号</el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <Table
        :columns="columns"
        :showPagination="true"
        :dataSource="tableData"
        :fetch="loadDataList"
        :options="tableOptions"
      >
        <!-- 文章信息 -->
        <template #userInfo="{ index, row }">
          <div>昵称:{{ row.nickName }}</div>
          <div>手机号:{{ row.phone }}</div>
          <div>职业:{{ row.profession }}</div>
        </template>
        <!-- 类型 -->
        <template #typeName="{ index, row }">
          <div>
            类型: <span v-if="row.type == 0">原创</span>
            <span v-if="row.type == 1">转载</span>
          </div>
          <div v-if="row.type == 1">转载地址:{{ row.reprintUrl }}</div>
        </template>
        <template #avatar="{ index, row }">
          <Cover :cover="row.avatar"></Cover>
        </template>
        <!-- 已发布：绿色，未发布，红色 -->
        <template #statusName="{ index, row }">
          <span v-if="row.status == 1" :style="{ color: 'green' }">{{
            row.statusName
          }}</span>
          <span v-else :style="{ color: 'red' }">{{ row.statusName }}</span>
        </template>
        <!-- 文章信息 -->
        <template #time="{ index, row }">
          <div>创建时间:{{ row.createTime }}</div>
        </template>
        <template #op="{ index, row }">
          <div class="op" v-if="userInfo.roleType === 1">
            <a
              href="javascript:void(0)"
              class="a-link"
              @click="showEditUser('update', row)"
              >修改</a
            >
            <el-divider direction="vertical" />
            <a
              href="javascript:void(0)"
              class="a-link"
              @click="updateStatus(row)"
            >
              <span v-if="row.status == 1">禁用</span>
              <span v-if="row.status == 0">启用</span>
            </a>
            <el-divider direction="vertical" />
            <a
              href="javascript:void(0)"
              class="a-link"
              @click="changePWD(row.userId)"
              >修改密码</a
            >
            <el-divider direction="vertical" />
            <a href="javascript:void(0)" class="a-link" @click="delUser(row)"
              >删除</a
            >
          </div>
        </template>
      </Table>
    </div>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      @close="dialogConfig.show = false"
      :width="dialogConfig.width"
      ><el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="100px"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item prop="userId" v-model="formData.userId">
            </el-form-item>
            <el-form-item prop="avatar" label="头像 ">
              <CoverUpload v-model="formData.avatar"></CoverUpload>
            </el-form-item>
            <el-form-item prop="nickName" label="昵称">
              <el-input
                placeholder="请输入昵称"
                v-model.trim="formData.nickName"
                size="large"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="phone" label="手机号">
              <el-input
                placeholder="请输入手机号"
                v-model.trim="formData.phone"
                size="large"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码" v-if="!formData.userId">
              <el-input
                placeholder="请输入密码"
                type="password"
                v-model.trim="formData.password"
                size="large"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              prop="rePassword"
              label="确认密码 "
              v-if="!formData.userId"
            >
              <el-input
                placeholder="请再次输入密码"
                type="password"
                v-model.trim="formData.rePassword"
                size="large"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="editorType" label="默认编辑器">
              <el-radio-group v-model="formData.editorType">
                <el-radio :value="0">富文本</el-radio>
                <el-radio :value="1">Markdown</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="profession" label="职业">
              <el-input
                placeholder="请输入职业"
                v-model.trim="formData.profession"
                size="large"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="16">
            <el-form-item prop="introduction" label="简介">
              <EditorHtml
                v-model="formData.introduction"
                :height="editorHtmlHeight"
              ></EditorHtml>
            </el-form-item>
          </el-col>
        </el-row> </el-form
    ></Dialog>
    <Dialog
      :show="pwdDialogConfig.show"
      :title="pwdDialogConfig.title"
      :buttons="pwdDialogConfig.buttons"
      @close="pwdDialogConfig.show = false"
      ><el-form
        :model="pwdFormData"
        :rules="rules2"
        ref="pwdFormDataRef"
        label-width="100px"
      >
        <el-form-item prop="password" label="密码 ">
          <el-input
            placeholder="请输入密码"
            type="password"
            v-model.trim="pwdFormData.password"
            size="large"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="rePassword" label="确认密码 ">
          <el-input
            placeholder="请再次输入密码"
            type="password"
            v-model.trim="pwdFormData.rePassword"
            size="large"
          >
          </el-input>
        </el-form-item> </el-form
    ></Dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
const searchFormData = ref({});
const tableData = reactive({});
const pwdFormData = ref({});
const pwdFormDataRef = ref(null);
const formData = ref({});
const { proxy } = getCurrentInstance();
const userInfo = ref(proxy.VueCookies.get("userInfo"));
const api = {
  loadUser: "setting/loadUser",
  updateStatus: "setting/updateStatus",
  saveTeamUser: "setting/saveTeamUser",
  getUserInfo: "getUserInfo",
  delUser: "setting/delUser",
  updatePassword: "setting/updatePassword",
};
const editPWD = ref(true);
const tableOptions = { extHeight: 38 };
const formDataRef = ref(null);

const columns = [
  {
    label: "头像",
    prop: "avatar",
    width: 150,
    scopedSlots: "avatar",
  },
  {
    label: "用户信息",
    prop: "userInfo",
    width: 300,
    scopedSlots: "userInfo",
  },
  {
    label: "编辑器",
    prop: "editorTypeName",
    width: 150,
  },
  {
    label: "角色",
    prop: "roleTypeName",
    width: 100,
  },
  {
    label: "状态",
    prop: "statusName",
    width: 100,
    scopedSlots: "statusName",
  },
  {
    label: "时间",
    prop: "time",
    width: 300,
    scopedSlots: "time",
  },
  {
    label: "操作",
    prop: "op",
    width: 250,
    scopedSlots: "op",
  },
];

const rules = {
  nickName: [{ required: true, message: "昵称不能为空" }],
  editorType: [{ required: true, message: "请选择默认编辑器" }],
  phone: [
    { required: true, message: "请输入手机号" },
    {
      validator: proxy.Verify.validatePhone,
      trigger: "blur",
      message: "请输入正确的手机号",
    },
  ],
  password: [
    { required: true, message: "请输入密码" },
    {
      validator: proxy.Verify.validatePassword,
      trigger: "blur",
      message: "密码最少8位，包含至少一个大写字母、一个小写字母和一个数字",
    },
  ],
  rePassword: [
    { required: true, message: "请再次输入密码" },
    {
      validator: checkPwd,
      trigger: "blur",
      message: "两次密码输入不一致",
    },
  ],
};

const rules2 = {
  password: [
    { required: true, message: "请输入密码" },
    {
      validator: proxy.Verify.validatePassword,
      trigger: "blur",
      message: "密码最少8位，包含至少一个大写字母、一个小写字母和一个数字",
    },
  ],
  rePassword: [
    { required: true, message: "请再次输入密码" },
    {
      validator: checkPwd2,
      trigger: "blur",
      message: "两次密码输入不一致",
    },
  ],
};

// 确认密码
function checkPwd(rule, value, callback) {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== formData.value.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
}

// 确认密码
function checkPwd2(rule, value, callback) {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== pwdFormData.value.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
}

const loadDataList = async () => {
  let params = {
    pageNo: tableData.pageNo,
    pageSize: tableData.pageSize,
  };
  Object.assign(params, searchFormData.value);
  //   console.log(params);
  let result = await proxy.Request({
    url: api.loadUser,
    params,
  });
  if (!result) {
    return;
  }
  // console.log(result.data);
  Object.assign(tableData, result.data);
  // tableData.list = result.data;
};

const updateStatus = (data) => {
  const info1 = data.status === 1 ? `你确定要禁用吗` : `你确定要启用吗`;
  const status = data.status === 1 ? "0" : "1";
  proxy.Confirm(info1, async () => {
    let result = await proxy.Request({
      url: api.updateStatus,
      params: {
        userId: data.userId,
        status: status,
      },
    });
    if (!result) {
      return;
    }
    loadDataList();
  });
};

const dialogConfig = reactive({
  show: false,
  title: "标题",
  width: "1200px",
  buttons: [
    {
      type: "danger",
      text: "确定",
      click: (e) => {
        saveMyInfo();
      },
    },
  ],
});

const pwdDialogConfig = reactive({
  show: false,
  title: "标题",
  width: "1200px",
  buttons: [
    {
      type: "danger",
      text: "确定",
      click: (e) => {
        submitPWDForm();
      },
    },
  ],
});

const showEditUser = (type, data) => {
  dialogConfig.show = true;
  if (type === "add") {
    nextTick(() => {
      formDataRef.value.resetFields();
      formData.value = {};
    });
  } else {
    formData.value = data;
    editPWD.value = false;
  }
};

const saveMyInfo = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) return;
    let params = {};
    params = formData.value;
    let result = await proxy.Request({
      url: api.saveTeamUser,
      params: params,
    });
    if (!result) {
      return;
    }
    const message = params.userId ? "修改成功" : "添加成功";
    ElMessage.success(message);
    dialogConfig.show = false;
  });
};

const getUserInfo = async () => {
  let result = await proxy.Request({
    url: api.getUserInfo,
  });
  if (!result) {
    return;
  }
  formData.value = result.data;
};

const delUser = (user) => {
  proxy.Confirm(`你确定要删除吗？`, async () => {
    let result = await proxy.Request({
      url: api.delUser,
      params: {
        userId: user.userId,
      },
    });
    if (!result) {
      return;
    }
    ElMessage.success("删除成功");
    loadDataList();
  });
};

const currentUserId = ref(null);
const changePWD = (userId) => {
  currentUserId.value = userId;
  pwdDialogConfig.show = true;
  nextTick(() => {
    pwdFormDataRef.value.resetFields();
    pwdFormData.value = {};
  });
};

// 修改密码
const submitPWDForm = () => {
  pwdFormDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let result = await proxy.Request({
      url: api.updatePassword,
      params: {
        password: pwdFormData.value.password,
        userId: currentUserId.value,
      },
    });
    if (!result) {
      return;
    }
    ElMessage.success("修改成功");
    pwdDialogConfig.show = false;
    currentUserId.value = null;
    // emit("callback");
  });
};
</script>

<style lang="scss" scoped></style>
